package com.shibo.generator.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/*
 * 通过io生成类
 * */
public class IoUtils extends org.apache.commons.io.FileUtils {

    private static Logger log = LoggerFactory.getLogger(IoUtils.class);

    /*
     * 生成文件
     * */
    public static void write(String path, String pathName, String txt){
        createDir(path);
        File file = new File(path,pathName+".java");
        FileWriter fw = null;
        BufferedWriter writer = null;
        try {
            boolean newFile = file.createNewFile();
            if (!newFile) file.mkdir();
            fw = new FileWriter(file);
            writer = new BufferedWriter(fw);
            writer.write(txt);
            writer.newLine();//换行
            writer.flush();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
    * 读取文件
    * */
    public String read(String pathName) {
        try {
            //文件读取
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(pathName);
            StringBuffer stringBuffer=new StringBuffer();//用于解析文件
            byte[] buff=new byte[1024];
            int btr;
            while ((btr = inputStream.read(buff)) !=-1){
                stringBuffer.append(new String(buff,0,btr, StandardCharsets.UTF_8));
            }
            inputStream.close();
            System.out.println(stringBuffer);
            return stringBuffer.toString();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 创建文件夹
     * */
    private static void createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            log.error("创建文件夹" + destDirName + "失败，文件夹已存在");
            return;
        }

        //创建目录
        if (!destDirName.endsWith(File.separator)) {
              destDirName += File.separator;
        }

        if (dir.mkdirs())
            log.info("创建目录" + destDirName + "成功！");
         else
            log.info("创建目录" + destDirName + "失败！");

    }


}
